package Day2025_02_28;


class ListNode {
    int val;ListNode next;
    ListNode() {}
    ListNode(int val) { this.val = val; }
    ListNode(int val, ListNode next) { this.val = val; this.next = next; }
}

public class LeetCode2 {
    public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
        ListNode head = new ListNode(0);
        ListNode prev = head;
        ListNode cur1 = l1, cur2 = l2;
        int ret = 0;
        while (cur1 != null || cur2 != null || ret!= 0) {
            int tmp = 0;
            if (cur1 != null) {
                ret += cur1.val;
                cur1 = cur1.next;
            }
            if (cur2 != null) {
                ret += cur2.val;
                cur2 = cur2.next;
            }
            prev.next = new ListNode(ret % 10);
            prev = prev.next;
            ret /= 10;
        }
        return head.next;
    }

    public ListNode addTwoNumbers2(ListNode l1, ListNode l2) {
        ListNode head = new ListNode(0);
        ListNode prev = head;
        ListNode cur1 = l1, cur2 = l2;
        int ret = 0;
        while (cur1 != null || cur2 != null || ret != 0) {
            int tmp = 0;
            if (cur1 != null) {
                tmp += cur1.val;
                cur1 = cur1.next;
            }
            if (cur2 != null) {
                tmp += cur2.val;
                cur2 = cur2.next;
            }
            if (ret != 0) tmp += ret;
            ret = tmp / 10;
            prev.next = new ListNode(tmp % 10);
            prev = prev.next;
        }
        return head.next;
    }
}
